package cn.it.shop.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
/*
 * AbstractInterceptor 是单个拦截器为单位的, 可以拦截所有方法
 * MethodFilterInterceptor：基于Action的方法拦截器, 细粒度更细, 把需要拦截的方法,配置即可
 * Interceptor--->AbstractInterceptor--->MethodFilterInterceptor
 * */
public class AccountInterceptor extends MethodFilterInterceptor {

	private static final long serialVersionUID = 9128767260097158015L;

	@Override
	protected String doIntercept(ActionInvocation invocation) throws Exception {
		System.out.println("---doIntercept--");
		// 1: 从session中获取account相关信息
		ActionContext actionContext = invocation.getInvocationContext();
		// 先获取request内置对象
		HttpServletRequest request=(HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);
		// 防止在地址栏直接输入网址, 防止 user 登陆成功后, 在地址栏输入 admin才能访问的url
		String preUrl=request.getHeader("referer");
		if(preUrl!=null){
			// 判断session中是否有account对象
			Object obj=request.getSession().getAttribute("account");
			if(obj!=null){
				return invocation.invoke();
			}else{	
				request.setAttribute("error", "请登陆!");
				return "alogin";
			}
		}else{
			request.setAttribute("error", "非法地址");
			return "alogin";
		}
	}

}
